package top.wardyan.sqlchecker.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.jfinal.kit.Prop;

import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.log.Log;
import top.wardyan.base.common.config.ConfigProp;

public class CustomizeShellUtil {
	
	private static Log log = Log.get();
	private static final Prop PROP = ConfigProp.load().appendIfExists("shellcmds.txt");

	// 这些指令要放到配置文件里
//	private static final String SHELL_MKDIR = "mkdir ~/sqlcheck";
//	private static final String SHELL_MKDIR_REMOTES = "mkdir ~/sqlcheck/locals";
//	private static final String SHELL_MKDIR_LOCALS = "mkdir ~/sqlcheck/remotes";
//	private static final String SHELL_MOUNT = "echo \"0400923\" | sudo -S mount -t cifs -o username=feng,password=0400923 //192.168.0.172/mes_sql_xh ~/sqlcheck/remotes";
//	private static final String SHELL_RSYNC = "rsync -raz --files-from=<(find ./ -mtime -3) ~/sqlcheck/remotes ~/sqlcheck/locals";

	private static final String SHELL_MKDIR = PROP.get("SQLCHECKER_MKDIR", "");
	private static final String SHELL_MKDIR_REMOTES = PROP.get("SQLCHECKER_MKDIR_REMOTES", "");
	private static final String SHELL_MKDIR_LOCALS = PROP.get("SQLCHECKER_MKDIR_LOCALS", "");
	private static final String SHELL_MOUNT = PROP.get("SQLCHECKER_MOUNT", "");
	private static final String SHELL_RSYNC = PROP.get("SQLCHECKER_RSYNC", "");
	
	public static Boolean exec(String cmd) {
		Boolean rs = false;
		try {
			Console.log(cmd);
		    Process process = Runtime.getRuntime().exec(cmd);
		    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
		    String line;
		    while ((line = reader.readLine()) != null) {
		        System.out.println(line);
		    }
		    process.waitFor();
		    rs = true;
		} catch (IOException | InterruptedException e) {
			rs = false;
		    log.error(e);
		}
		Console.log("RESULT:", cmd, rs);
		return rs;
	}

	public static Boolean deal() {
		Boolean rs = false;
		
//		exec(SHELL_MKDIR);
//		exec(SHELL_MKDIR_REMOTES);
//		exec(SHELL_MKDIR_LOCALS);
//		exec(SHELL_MOUNT);
		rs = exec(SHELL_RSYNC);
		return rs;
	}
	
	public static void main(String[] args) {
		// 要支持下载脚本
		exec("pwd");
		deal();
		ThreadUtil.sleep(10000);
		// exec("echo $PATH");
	}
}
